<?php
namespace controller;

/**
 * klasa do obsługi produktu
 *
 * @author Damian
 */
class Shop_Product extends Shop{
    public function index(){
        
      $productURL= \library\RequestMethods::get("productURL");
        if (!$productURL) {
            throw  new \model\exceptions\PropertyNotExistsException("pod adresem {$productURL} nie ma produktu");
        }
        $session= \library\Registry::get("session");
       $customer = $session->get("customer");
        $productCriteria = new \model\Criteria();
        $productCriteria->from(\model\TblProduct::getModel()->getTable())
                ->where(\model\TblProduct::URL, "=", $productURL,  \model\TblProduct::getModel()->getTable())
                ->where(\model\TblProduct::ACTIVE, "=", 1,  \model\TblProduct::getModel()->getTable(), " and ")
                ->where(\model\TblProduct::VISABLE, "=", 1,  \model\TblProduct::getModel()->getTable(), " and ")
                ->where(\model\TblProduct::SHOP_ID, "=", $this->shop->ShopID,  \model\TblProduct::getModel()->getTable(), " and ")
                ->join(\model\TblManufacturer::getModel())
                ->join(\model\TblCategory::getModel());
        $product = \model\TblProduct::getModel()->first($productCriteria);
        $view = $this->getActionView();
         $layoutView = $this->getLayoutView();
        if(!$product){
            $view->set("error","Podany produkt nie został odnaleziony");
            $layoutView->set("paneltitle", "Podany produkt nie został odnaleziony");
            $this->render();
            return;
        }
        //opinie
       $opinionCriteria = new \model\Criteria();
       $opinionCriteria->from(\model\TblOpinion::getModel()->getTable())
               ->join(\model\TblCustomer::getModel())
              ->join(\model\TblPerson::getModel())
               ->where(\model\TblOpinion::PRODUCT_ID, "=", $product->ProductID)
               ->where(\model\TblOpinion::SHOP_ID, "=", $this->shop->ShopID,  \model\TblOpinion::getModel()->getTable()," and ");
       $opinions = \model\TblOpinion::getModel()->all($opinionCriteria);
       $avg=0;
       $allOpinions=0;
       if ($opinions){
           $opinionDataTable = new \model\DataTable( $opinions);
           //var_dump($opinion["CustomerID"][key($opinion["CustomerID"])]["PersonID"][key($opinion["CustomerID"][key($opinion["CustomerID"])]["PersonID"])]);
          // echo key($opinion["CustomerID"][key($opinion["CustomerID"])]["PersonID"]);
          // var_dump($opinionDataTable);
           $view->set("opinions",$opinionDataTable->getModelData());
           $opinionCount=array();
           $avg=0;
           for ($i=1;$i<=5;$i++){
               $CountCriteria = new \model\Criteria();
              $opinionCount[$i]= (int)$CountCriteria->from(\model\TblOpinion::getModel()->getTable())
               ->where(\model\TblOpinion::PRODUCT_ID, "=", $product->ProductID)
               ->where(\model\TblOpinion::SHOP_ID, "=", $this->shop->ShopID,false," and ")
                       ->where(\model\TblOpinion::MARK, "=", $i,false," and ")->count();
              $allOpinions+=$opinionCount[$i];
              $avg+=$opinionCount[$i]*$i;
           }
           $avg2 =$avg/$allOpinions;
           $stars = new \view\StarSet($avg2,5,25);
           $view->set("avg",round($avg2,2));
           $view->set("stars",$stars);
           $view->set("allOpinions",$allOpinions);
           $view->set("opinionCount",$opinionCount);
       }
        if (\library\RequestMethods::post("mark") && $customer){
            $date = new \DateTime();
            $mark = \library\RequestMethods::post("mark");
            $content = (\library\RequestMethods::post("content"))? \library\RequestMethods::post("content"): "Brak oceny opisowej";
            $ip = $this->getRealIpAddr();
            $type="produkt";
            $opinion = new \model\TblOpinion([
            \model\TblOpinion::SHOP_ID=>  $this->shop->ShopID,
            \model\TblOpinion::PRODUCT_ID =>$product->ProductID,
            \model\TblOpinion::IP =>$ip,
            \model\TblOpinion::ADDITION_DATE=>$date->format('Y-m-d H:i:s'),
            \model\TblOpinion::MARK =>$mark,
            \model\TblOpinion::MODERATED=>0,
            \model\TblOpinion::CONTENT=>$content,
            \model\TblOpinion::OPINION_TYPE =>$type,
            \model\TblOpinion::CUSTOMER_ID =>$customer->CustomerID
            ]);
            $product->AvgMark=($avg+$mark)/($allOpinions+1);
            $product->save();
            $opinion->save();            
            return;
        }
        $layoutView->set("paneltitle", "Dane produktu " . $product->Name);
        $picturesCriteria = new \model\Criteria();
        $picturesCriteria->from(\model\TblProductPicture::getModel()->getTable())
                ->join(\model\TblPicture::getModel())
                ->limit(10)
                ->where(\model\TblProductPicture::PRODUCT_ID, "=", $product->ProductID);
        $pictures = \model\TblPicture::getModel()->all($picturesCriteria);     
        //$picturesDataTable = new \model\DataTable($pictures, true, "PictureID");
        $relatedProdutcs = \model\TblRelatedProduct::findRelatedProducts($product->ProductID, $this->shop->ShopID);
        $relatedProdutcsByOrder = \model\TblProductOrder::findRelatedProducts($product->ProductID);
        $featuresCriteria = new \model\Criteria();

        $featuresCriteria->from(\model\TblFeatureValue::getModel()->getTable())
                ->join(\model\TblProductFeature::getModel())
                ->join(\model\TblCategoryFeature::getModel())
                ->where(\model\TblProductFeature::PRODUCT_ID, "=", $product->ProductID);
        $features = \model\TblCategoryFeature::getModel()->all($featuresCriteria);
        $featuresDataTable = new \model\DataTable($features,false);
       // var_dump($featuresDataTable);
       // \model\TblProductOrder::findRelatedProducts($product->ProductID);
       // var_dump($product);
       foreach ($pictures as $picture){
           if ($picture->DefaultPicture==1){
               $view->set("MainPicture",$picture);
               break;
           }
       }
       $view->set("relatedProdutcsByOrder",$relatedProdutcsByOrder);
       if ($relatedProdutcs){
           $view->set("related",$relatedProdutcs->getModelData(true));
       }
       else {
           $view->set("related",false);
       }
       
      // var_dump($_SESSION);
       $view->set("customer",$customer);
       $date = new \DateTime();
       $LogWatch = new \model\TblLogWatch([
       \model\TblLogWatch::PRODUCT_ID =>$product->ProductID,
       \model\TblLogWatch::SHOP_ID =>  $this->shop->ShopID,
       \model\TblLogWatch::IP =>  $this->getRealIpAddr(),
       \model\TblLogWatch::WATCH_DATE =>$date->format('Y-m-d H:i:s')
       ]);
       if ($customer){
           $LogWatch->CustomerID=$customer->CustomerID;
       }
       $LogWatch->save();
        $view->set("product",$product);
       // var_dump($featuresDataTable->getModelData(true));
        $view->set("features",$featuresDataTable->getModelData(false));
       // var_dump($picturesDataTable->getModelData(true));
        $view->set("pictures",$pictures);
      //  $view->set("productpicture",$productPicture);
        $this->render();
    }
    public static function showGeneral($url){
        
        
        
    }
}
